package com.java.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.java.pojo.UserAddress;
import com.java.pojo.bo.AddressBO;
import com.java.service.UserAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.java.common.utils.PageUtils;
import com.java.common.utils.R;

import javax.validation.Valid;


/**
 * 用户地址表
 *
 * @author jl
 * @since 2020-10-13 11:31:41
 */
@Api(tags = "用户收货地址管理")
@RestController
@RequestMapping("/address")
public class UserAddressController {
    @Autowired
    private UserAddressService userAddressService;

    @ApiOperation("设置默认地址")
    @PostMapping("/setDefault")
    public R setDefault(@RequestParam String userId,@RequestParam String addressId) {
        userAddressService.updateUserAddressToBeDefault(userId,addressId);
        return R.ok();
    }

    @ApiOperation("删除用户地址表")
    @PostMapping("/delete")
    public R delete(@RequestParam String userId,@RequestParam String addressId) {
        userAddressService.remove(new LambdaQueryWrapper<UserAddress>().eq(UserAddress::getUserId,userId).eq(UserAddress::getId,addressId));
        return R.ok();
    }

    @ApiOperation("修改用户地址表")
    @PostMapping("/update")
    public R update(@RequestBody @Valid AddressBO addressBO) {
        if (StrUtil.isBlank(addressBO.getAddressId())) {
            return R.error("用户ID不能为空");
        }
        userAddressService.updateUserAddress(addressBO);
        return R.ok();
    }

    @ApiOperation("新增用户地址表")
    @PostMapping("/add")
    public R save(@RequestBody @Valid AddressBO addressBO) {
        userAddressService.addNewUserAddress(addressBO);
        return R.ok();
    }

    @ApiOperation("根据用户ID查询收货地址列表")
    @PostMapping("/list")
    public R list(@RequestParam String userId) {
        List<UserAddress> list = userAddressService.list(new LambdaQueryWrapper<UserAddress>().eq(UserAddress::getUserId, userId));
        return R.ok(list);
    }

    /**
     * 带条件分页查询用户地址表
     */
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = userAddressService.queryPage(params);

        return R.ok(page);
    }


    /**
     * 根据主键查询用户地址表
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") String id) {
        UserAddress userAddress = userAddressService.getById(id);

        return R.ok(userAddress);
    }
}
